package com.example.ktpspringboot.utils;

import com.example.ktpspringboot.entity.FileVO;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUtil {
    private static SimpleDateFormat sfFile = new SimpleDateFormat("yyyyMMddHHmmss");

    public static FileVO handleFileSave(String localPath, MultipartFile file) throws Exception {
        // 处理传来的文件
        String name = file.getOriginalFilename();
        String saveName = "file-" + sfFile.format(new Date()) + UUID.randomUUID().toString().substring(0, 4) + name.substring(name.lastIndexOf("."));
        File saveFile = new File(localPath + saveName);
        file.transferTo(saveFile);


        if (Files.probeContentType(saveFile.toPath()) != null) {
            return new FileVO(name, saveName, Files.probeContentType(saveFile.toPath()).startsWith("image/"));
        } else {
            return new FileVO(name, saveName, false);
        }
    }

    public static boolean downloadFile(File file, String fileName, HttpServletResponse response) throws Exception {
        // 清空缓冲区，状态码和响应头(headers)
        response.reset();
        // 设置ContentType，响应内容为二进制数据流，编码为utf-8，此处设定的编码是文件内容的编码
        response.setContentType("application/octet-stream;charset=utf-8");
        // 以（Content-Disposition: attachment; filename="filename.jpg"）格式设定默认文件名，设定utf编码，此处的编码是文件名的编码，使能正确显示中文文件名
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "utf-8"));

        // 实现文件下载
        byte[] buffer = new byte[1024 * 1024 * 1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            // 获取字节流
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
